

package XMLParser;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

 
public class MyXMLWriter {

    private String tempFileName;
    private BufferedWriter out;
    private List<String> tags = new ArrayList<String>();
    int flag = 0;

    public MyXMLWriter(String tempfile)
    {
        tempFileName = tempfile;
    }

    public void setFileName(String f){tempFileName = f;}
    public String getFileName(){return tempFileName;}

    public void SetTags(List<String> list){tags = list;}
    public void Add(List list)
    {
       try {
       if (flag == 1)
                {
                    String  str = "</" + tags.get(1) + ">";
                    out.write(str);
                    out.newLine();
                }
        for(int i=1; i<tags.size(); i++)
        {
           
                String str = "";
               
                if((i==1) && ((String)list.get(0)).equalsIgnoreCase(""))
                {
                    flag = 1;
                    str = "  <" + tags.get(1) + ">";
                    

                }
                else
                {
                  // for(int j = 0;j<i; j++)
                       str += "      ";
                 str += "<" + tags.get(i) + ">"+list.get(i-1)+"</" + tags.get(i) + ">";
                }
                out.write(str);
                 out.newLine();
            }
        } catch (IOException ex) {
                Logger.getLogger(MyXMLWriter.class.getName()).log(Level.SEVERE, null, ex);
            }
        
    };
    public void Start()
    {
        try {
            out = new BufferedWriter(new FileWriter(tempFileName));
           // out.write("<?xml version=\"1.0\"?>");
          out.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>");

            out.newLine();
            out.write("<" + tags.get(0) + ">");
            out.newLine();
        } catch (IOException ex) {
            Logger.getLogger(MyXMLWriter.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
    public void Stop()
    {
        try {
            if (flag == 1){
            out.write("  </" + tags.get(1) + ">");
            out.newLine();
            }
            out.write("</" + tags.get(0) + ">");
            flag = 0;
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(MyXMLWriter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
